<template>
  <div class="option__item">
    <label :class="['client-logo__module mask__item',{'upload-image-border': borderShow}]" for="logoUploader" title="更换LOGO">
      <img :src="useImage | resourceUrl" class="image__item" v-if="useImage" />
      <i class="upload-icon__item el-icon-plus" v-else />
      <div class="upload-mask__item" v-show="uploading">
        <i class="el-icon-loading" />上传中...
      </div>
      <input @change="changeHandler" id="logoUploader" type="file" v-show="false" />
    </label>
    <ul class="upload-cover-suggest">
      <li>更换站点的logo。</li>
      <li>图片尺寸限制: {{ imageW }} x {{ imageH }}。</li>
    </ul>
  </div>
</template>

<script>
import { imageReader } from '@/utils';
import { clientHeaderUploaderAPI } from '@/api/utils';

export default {
    name: 'ClientLogo',
    props: {
        image: {
            type: String,
            default: '',
        },
    },
    data() {
        return {
            accept: 'image/jpeg, image/jpg, image/png, image/bmp',
            selfImage: '',
            imageW: 220,
            imageH: 105,
            uploading: false,
        };
    },
    computed: {
        useImage() {
            return this.selfImage || this.image;
        },
        borderShow() {
            return true;
        },
    },
    destroyed() {
        this.destroyObjectURL();
    },
    methods: {
        async changeHandler(evt) {
            const [file] = evt.target.files;
            this.destroyObjectURL();
            const imageURL = window.URL.createObjectURL(file);
            try {
                const { width, height } = await imageReader(imageURL);
                this.verifyImageSize(width, height);
                this.selfImage = imageURL;
                await this.uploadHandler(file);
            } catch (error) {
                this.$notify({ type: 'error', title: '设置LOGO出错', message: error.msg, offset: 60 });
            } finally {
                evt.target.value = null;
            }
        },
        verifyImageSize(width, height) {
            const { imageW, imageH } = this;
            if (width !== imageW || height !== imageH) {
                // eslint-disable-next-line no-throw-literal
                throw { msg: '图片尺寸错误!' };
            }
        },
        async uploadHandler(file) {
            this.uploading = true;
            await clientHeaderUploaderAPI(file, 'logo');
            this.uploading = false;
        },
        destroyObjectURL() {
            URL.revokeObjectURL(this.selfImage);
        },
    },
};
</script>

<style lang="scss">
.client-logo__module {
  width: 200px;
  height: 100px;
  position: relative;
  display: block;
  border-radius: 4px;
  cursor: pointer;
  &:hover .upload-icon__item {
    color: #fff;
  }
  .upload-icon__item {
    font-size: 20px;
  }
}
</style>
